//
//  AttendenceViewModel.m
//  JTFaceAttendence
//
//  Created by lj on 2021/7/1.
//

#import "AttendenceViewModel.h"
#import "NSString+Tool.h"
#import "JTFaceImageAttendenceManager.h"
#import "UDPSocketManager.h"

@interface AttendenceViewModel ()

@property (nonatomic, strong) UDPSocketManager *manager;

@end

@implementation AttendenceViewModel

- (instancetype)init {
    if (self = [super init]) {
        
    }
    return self;
}

- (void)requestAttendence:(NSString *)imgStr {
    
    if (!imgStr ) return;
    NSString *imgDataStr = imgStr;
    //参数处理+
    NSDictionary *dict = @{@"Base64Image":imgDataStr,@"verifyToken":AdminInfo.shareInfo.verifyToken,@"placeId":AdminInfo.shareInfo.placeId};
    NSMutableArray *marr = [NSMutableArray array];
    for (NSString *key in dict.allKeys) {
        [marr addObject:[NSString stringWithFormat:@"%@=%@",key,dict[key]]];
    }
    NSString *bodyStr = [[marr componentsJoinedByString:@"&"] stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSURL *url = [NSURL URLWithString:@"https://cloud.hzjtyh.com/api/pc/home/findFace"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30];
    [request setHTTPMethod:@"POST"];
    [request addValue:@"application/x-www-form-urlencoded;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    request.HTTPBody = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    DLog(@"%@",request.HTTPBody);
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    configuration.requestCachePolicy = NSURLRequestReloadIgnoringCacheData;
    configuration.timeoutIntervalForRequest = 30;
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data) {
            NSMutableDictionary *responseDic = [NSJSONSerialization JSONObjectWithData: data
                                                                               options: NSJSONReadingMutableContainers
                                                                                 error: &error];
            dispatch_async(dispatch_get_main_queue(), ^{
                DLog(@"%@",responseDic);
                NSDictionary *responseDict = (NSDictionary *)responseDic;
                NSString *msg = responseDict[@"msg"];
                NSNumber *num = responseDict[@"error_code"];
                NSDictionary *data = responseDict[@"data"];
                if ([num isEqualToNumber:@(0)]) {
                    if ([[AdminInfo shareInfo].adapterAppID intValue] == 1) {
                        if (self.udpResultBlock) {
                            self.udpResultBlock(data);
                        }
                    } else {
                        
                        [JTFaceImageAttendenceManager sharedInstance].lastEmpModel = data;
                        [self plusAttendence];
                    }
                } else {
                    if (self.attendentBlock) {
                        self.attendentBlock(NO,msg);
                    }
                }
            });
        } else {
            if (self.attendentBlock) {
                self.attendentBlock(NO,error.localizedDescription);
            }
        }
    }];
    [task resume];
}

- (void)requestLivenessAttendenceLogId:(NSString *)log_id {
    //参数处理+
    NSDictionary *dict = @{@"log_id":log_id,@"verify_token":AdminInfo.shareInfo.verifyToken,@"placeId":AdminInfo.shareInfo.placeId};
    NSMutableArray *marr = [NSMutableArray array];
    for (NSString *key in dict.allKeys) {
        [marr addObject:[NSString stringWithFormat:@"%@=%@",key,dict[key]]];
    }
    NSString *bodyStr = [marr componentsJoinedByString:@"&"];
    DLog(@"%@",bodyStr);
    NSURL *url = [NSURL URLWithString:@"https://cloud.hzjtyh.com/api/pc/home/findFaceV4"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30];
    [request setHTTPMethod:@"POST"];
    [request addValue:@"application/x-www-form-urlencoded;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    request.HTTPBody = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    configuration.requestCachePolicy = NSURLRequestReloadIgnoringCacheData;
    configuration.timeoutIntervalForRequest = 30;
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data) {
            NSMutableDictionary *responseDic = [NSJSONSerialization JSONObjectWithData: data
                                                                               options: NSJSONReadingMutableContainers
                                                                                 error: &error];
            dispatch_async(dispatch_get_main_queue(), ^{
                DLog(@"%@",responseDic);
                NSDictionary *responseDict = (NSDictionary *)responseDic;
                NSString *msg = responseDict[@"msg"];
                NSNumber *num = responseDict[@"error_code"];
                NSDictionary *data = responseDict[@"data"];
                if ([num isEqualToNumber:@(0)]) {
                    if ([[AdminInfo shareInfo].adapterAppID intValue] == 1) {
                        if (self.udpResultBlock) {
                            self.udpResultBlock(data);
                        }
                    } else {
                        [JTFaceImageAttendenceManager sharedInstance].lastEmpModel = data;
                        [self plusAttendence];
                    }
                } else {
                    if (self.attendentBlock) {
                        self.attendentBlock(NO,msg);
                    }
                }
            });
        } else {
            if (self.attendentBlock) {
                self.attendentBlock(NO,error.localizedDescription);
            }
        }
    }];
    [task resume];
}

- (void)plusAttendence {
    //日期处理
    NSDate *date = [NSDate date];
    NSTimeInterval interval = [date timeIntervalSince1970];
    NSString *intervalStr = [NSString stringWithFormat:@"%.0f",interval*10000];
    //32位随机数
    NSString *nonceStr = [NSString stringWithFormat:@"%ld",(long)(arc4random()*pow(10, 31))];
    //sign 签名
    NSString *secretKey = @"7dkc86acd1438f1";
    NSString *placeKey = AdminInfo.shareInfo.placeKey;
    NSString *paramStr = [NSString stringWithFormat:@"%@%@%@",JTFaceImageAttendenceManager.sharedInstance.lastEmpModel[@"empCode"], intervalStr,nonceStr];
    NSString *signStr = [paramStr HmacSHA256WithSecretKey:secretKey];
    NSDictionary *dict = @{@"empNo":JTFaceImageAttendenceManager.sharedInstance.lastEmpModel[@"empCode"],@"placeKey":placeKey,@"timestamp":intervalStr,@"nonceStr":nonceStr, @"sign":signStr};
    NSMutableArray *marr = [NSMutableArray array];
    for (NSString *key in dict.allKeys) {
        [marr addObject:[NSString stringWithFormat:@"%@=%@",key,dict[key]]];
    }
    NSString *bodyStr = [marr componentsJoinedByString:@"&"];
    NSURL *url = [NSURL URLWithString:@"https://reapi.hzjtyh.com/v1/pc/doFaceAttendance"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30];
    [request setHTTPMethod:@"POST"];
    [request addValue:@"application/x-www-form-urlencoded;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    request.HTTPBody = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    configuration.requestCachePolicy = NSURLRequestReloadIgnoringCacheData;
    configuration.timeoutIntervalForRequest = 30;
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data) {
            NSMutableDictionary *responseDic = [NSJSONSerialization JSONObjectWithData: data
                                                                               options: NSJSONReadingMutableContainers
                                                                                 error: &error];
            dispatch_async(dispatch_get_main_queue(), ^{
                DLog(@"%@",responseDic);
                NSDictionary *responseDict = (NSDictionary *)responseDic;
                NSString *msg = responseDict[@"msg"];
                NSNumber *num = responseDict[@"code"];
                NSDictionary *data = responseDict[@"data"];
                if ([num isEqualToNumber:@(0)]) {
                    [JTFaceImageAttendenceManager sharedInstance].lastEmpModel = data;
                    if (self.attendentBlock) {
                        self.attendentBlock(YES,msg);
                    }
                } else {
                    if (self.attendentBlock) {
                        self.attendentBlock(NO,msg);
                    }
                }
            });
        } else {
            if (self.attendentBlock) {
                self.attendentBlock(NO,error.localizedDescription);
            }
        }
    }];
    [task resume];
}

@end
